const http = require('http')
const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser'); // 处理post 中 body的数据
const KoaJwt = require('koa-jwt')
// const cors = require('koa-cors')
const path = require('path')
const isProduction = process.env.NODE_ENV === 'production'
const {port, secret} = require('./config/index')
const static = require('koa-static')
// 引入路由分发
const routerAdmin = require('./router')

// 导入controller middleware:
const controller = require('./middleware/controller')
const staticFiles = require('./middleware/static-files')
const templating = require('./middleware/templating')
const errorHandle = require('./middleware/errorHandle')
// 使用middleware:
app.use(staticFiles('/static/', __dirname + '/static'))
app.use(bodyParser())

app.use(templating('views', {
    noCache: !isProduction,
    watch: !isProduction
}))

const staticPath = './static'
app.use(static(
  path.join( __dirname,  staticPath)
))
app.use(controller())

// 设置跨域访问
// app.use(cors())
app.use(errorHandle);
app.use(KoaJwt({secret: secret}).unless({
    path: [/\/register/, /\/login/, /\/dist/, /\/favicon/,]
}));

app.use(routerAdmin.routes());
app.use(router.routes());





app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});
http
    .createServer(app.callback())
    .listen(port, () => console.log(`✅  The server is running at http://localhost:${port}/`))
